package be.jhd.appserver;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import be.jhd.repository.Artifact;

public class DeployedArtifactAnalyzer {

	private final String deployedArtifacts;

	public DeployedArtifactAnalyzer(String deployedArtifacts) {
		this.deployedArtifacts = deployedArtifacts;
	}

	public DeployedArtifact find(Artifact artifact) {
		
		try{
			final String regex = buildRegEx(artifact);
			final Pattern p = Pattern.compile(regex);
			final Matcher m = p.matcher(deployedArtifacts);
			
			if(m.find()){
				final String appName = m.group();
				final String version = m.group(1);
				return new DeployedArtifact(artifact, version, appName);
			}
		
		}catch(Exception exc){
		}
		
		return new DeployedArtifact(artifact, "", "");
		
	}

	protected String buildRegEx(Artifact artifact) {
		final StringBuilder builder = new StringBuilder();
		builder.append(artifact.getArtifact()).
		append("-(.+)");
		if(artifact.isClassified()){
			builder.append("(.|-)").append(artifact.getClassifier());
		}
		builder.append(".").append(artifact.getPackaging());
		return builder.toString();
	}

}
